package com.apes.fn.scm.retailOrder.service;

import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.model.RetailOrderItem;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.account.model.AccountingMethod;
import com.apes.scm.account.account.model.InventoryMode;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherItem;
import com.apes.scm.voucher.repository.VoucherRepository;
import com.apes.scm.voucher.service.BusinessType;
import com.apes.scm.voucher.service.VoucherType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 	年卡销售
 * 		1.年卡销售走标准零售
 * 		2.年卡销售退货，走无原单退货
 * 	年卡置换
 * 		1.正向的走标准销售
 * 		2.退货的走无原单退货
 *
 * @author wuq
 * @create 2020-09-15 14:21
 */
@Service
public class YearCarVoucherService extends DomainService {

    @Autowired
    private VoucherRepository voucherRepository;

    /**
     * 兑换券置换负数单据走无原单退货
     *
     * @param request RetailOrder
     */
    public void returnCoupon(SimpleRequest request) {
        RetailOrder retailOrder = request.getO(RetailOrder.class);
        processReturn(retailOrder);
    }

    /**
     * 处理 年卡/年审退款、兑换券置换、e保养+ 逻辑
     * 无原单退货
     * @param retailOrder RetailOrder
     */
    private Voucher processReturn(RetailOrder retailOrder){
        Voucher voucher = getDefaultVoucher(retailOrder); // 销售退回
        voucher.setReturned(true);
        voucher.setInventoryMode(InventoryMode.IM_OWN);     //设置库存模式：自有
        voucher.setAccountingMethod(AccountingMethod.AM_PURCHASE);  // 核算方式：经销
        voucher.setCustomerExpand(retailOrder.getCustomerExpand().getId());

        // 通过原销售订单找原销售凭证，由于存在零售单产生分销单的销售凭证，这里加上 source 与 origin 的条件
        Voucher saleVoucher = new Voucher();
        List<Voucher> saleVouchers = voucherRepository.findAll(
                JpaDsl.toCriteriaByEq("voucherType", VoucherType.CUSTOMER_SALE, "source", retailOrder.getSource(), "origin", retailOrder.getSource()));
        if (saleVouchers.size() == 1 ) {
            saleVoucher = saleVouchers.get(0);
            voucher.setVoucher(saleVoucher);
        }

        final Voucher originSaleVoucher = saleVoucher;
        voucher.setVoucherItems( retailOrder.getSaleItems().stream().map(
                retailOrderItem -> {
                    VoucherItem voucherItem = getDefaultVoucherItem(retailOrderItem);

                    // 找原销售凭证中的明细行
                    if (Objects.nonNull(originSaleVoucher)) {
                        originSaleVoucher.getVoucherItems().forEach( saleVoucherItem -> {
                            if (retailOrderItem.getProduct().getId().equals(saleVoucherItem.getProduct().getId())) {
                                voucherItem.setVoucherItem(saleVoucherItem);
                            }
                        });
                    }

                    voucherItem.setOwner(retailOrder.getCompany());
                    return voucherItem;
                }).collect(Collectors.toSet()) );

        return invoke("voucher.create", MapUtil.mapped(voucher));
    }

    private Voucher getDefaultVoucher(RetailOrder retailOrder) {
        Voucher voucher = new Voucher();
        voucher.setDept(retailOrder.getDept());
        voucher.setCompany(retailOrder.getCompany());
        voucher.setPartner(retailOrder.getCompany().getParty().getPatyRoleByType("Customer"));
        voucher.setBusinessType(BusinessType.SALE_RETURN);
        voucher.setClerk(retailOrder.getClerk()); //业务员
        voucher.setScene(null);
        voucher.setOrigin(retailOrder.getId());
        voucher.setOriginBusinessType(retailOrder.getInnerBusinessType());
        voucher.setSource(retailOrder.getId());
        voucher.setSourceBusinessType(retailOrder.getInnerBusinessType());
        return voucher;
    }

    private VoucherItem getDefaultVoucherItem(RetailOrderItem item) {
        VoucherItem voucherItem = new VoucherItem();
        voucherItem.setProduct(item.getProduct());
        voucherItem.setTax(item.getTax());
        voucherItem.setOwner(item.getOwner());
        voucherItem.setUom(item.getUom());          // 设置为销售的单位以及数量
        voucherItem.setProductQty( -1 * Math.abs(item.getProductUomQty()) );
        voucherItem.setPriceUnit(item.getPriceUnit());      // 默认为零售单价
        voucherItem.setOriginItemId(item.getId());
        voucherItem.setSourceItemId(item.getId());
        return voucherItem;
    }
}
